// pages/index/mall/mall_order.js
var App = getApp();
let orderMoney = 0; //订单初始需要支付的价格
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userIsVip:false, //当前用户是不是vip
    orderMsg:[], //要提交的订单信息
    orginPrice:0, //商品原价
    discountPrice:'0.00', //优惠价格
    totalNum:0,
    address:'',
    phone:'',
    username:'',
    youhui:[], //优惠券张数
    youhuiPrice: 0, //优惠券减免
    vipMsg: {  //vip信息
      money: '5.00',
      msg:'首月5元，之后15元/月'
    }, 
    openVip:false, //开通vip
    vipDiscount:'10.00', //vip减免
    lastPayMoney:'0.00', //实际支付价格
    userMsgIsAll: true,//用户信息是否完善
    realOrderMoney:'0.00', //订单的实际价格
    userAccount:'0.00', //账户余额
    discountMsg:'' //优惠券信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync('coupon');//清空缓存的优惠券信息
    wx.removeStorageSync('discountIndex');//清空缓存的优惠券信息
    wx.showLoading({
      title: '加载中',
    })
    let list = JSON.parse(options.ordermsg);
    let num = 0;
    let is_vip = wx.getStorageSync('allUserMsg').vip.is_vip;//判断用户身份
    let youhui =0;//活动优惠减免

    for(let i=0;i<list.length;i++){
      num += list[i].buy_num
    }  

    if (is_vip) {
      orderMoney = parseFloat(options.origin-options.activeSave-options.vip_youhui) .toFixed(2);
    } else {
      orderMoney = parseFloat(options.total).toFixed(2);
    } 
  
    this.setData({
      userIsVip: is_vip,
      orginPrice: parseFloat(options.origin).toFixed(2), //商品原价
      lastPayMoney: orderMoney,
      orderMsg: list,
      totalNum: num,
      discountPrice: parseFloat(options.activeSave).toFixed(2),
      vipDiscount: parseFloat(options.vip_youhui).toFixed(2), //vip减免
      realOrderMoney: parseFloat(options.total).toFixed(2)
    })

     
    this.getBoxAddress();
    this.getDiscountInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let coupon = this.data.youhui;
    let index = wx.getStorageSync('discountIndex');
    if (index != '' && index > -1) {
      this.setData({
        youhuiPrice: coupon[index].scheme,
        discountMsg: '满' + coupon[index].rule + '减' + coupon[index].scheme
      })
    } else {
      this.setData({
        youhuiPrice: 0
      })
    }
    this.computeRealMoney();//计算价格
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //获取宿舍地址
  getBoxAddress: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/info', //接口地址
      data: {
        token: wx.getStorageSync('token'),
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          wx.hideLoading();
          let arr = res.data.data;
          let defaultName = arr.openid.slice(0, 10);
          if (arr.nickname == defaultName || arr.phone == null || arr.hostel==null){
            that.setData({
              userMsgIsAll: false
            })
          }else{
            that.setData({
              userMsgIsAll: true,
              phone: arr.phone,
              username: arr.nickname,
              address: arr.school + arr.floor + ' ' + arr.hostel
            })
          }      
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //开关
  vipSwitch: function () {
    this.setData({
      openVip: !this.data.openVip
    })
    this.computeRealMoney();//计算价格
  },

  // 计算最后价格
  computeRealMoney:function(){
    let vip_discount = parseFloat(this.data.vipDiscount); //优惠券折扣
    let vip_price = parseFloat(this.data.vipMsg.money); //vip价格
    let c_price = orderMoney - parseFloat(this.data.youhuiPrice); //不包含vip需支付的金额
    let youhui_discount = parseFloat(this.data.youhuiPrice);

    if(this.data.openVip){
      this.setData({
        lastPayMoney: parseFloat(c_price + vip_price - vip_discount).toFixed(2)
      })
    }else{
      this.setData({
        lastPayMoney: parseFloat(c_price).toFixed(2)
      })
    }
  },

  //去商品详情页
  goGoodsDetail:function(){
    wx.navigateTo({
      url: '/pages/index/mall/mall_order_goods?goods=' + JSON.stringify(this.data.orderMsg) + '&isVip=' + this.data.openVip
    })
  },

  //获取优惠信息
  getDiscountInfo: function () {
    let that = this;
    let goodsList = that.data.orderMsg;
    for (var i = 0; i < goodsList.length; i++) {//更新购买商品数量
      goodsList[i].number = goodsList[i].buy_num;
    }
    wx.request({
      url: App.data.globalAPI + '/order/mall/getinfo',
      data: {
        goods: goodsList,
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          let vipPrice = 'vipMsg.money'
          that.setData({
            userAccount: arr.data.money,
          })
          if (arr.data.vip_price != '-1') {
            that.setData({
              vipMsg: {
                money: arr.data.vip_price,
                msg: '现在开通' + parseFloat(arr.data.vip_price).toFixed(2) + '元/月'
              }
            })
          }
          if (arr.data.coupon.length > 0) {
            let vipPrice = 'vipMsg.money'
            that.setData({
              hasDiscount: true,//有可用优惠券
              youhui: arr.data.coupon,
            })
          } else {
            that.setData({
              hasDiscount: false,//无可用优惠券
            })
          }

        } else {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  // 提交订单
  submitOrder:function(){
    if (!this.data.userMsgIsAll){
      wx.showToast({
        title: '完善配送信息后提交',
        icon:'none'
      })
    }else{
      let that = this;
      let goodsList = that.data.orderMsg;
      let cpIndex = wx.getStorageSync('discountIndex');//使用第几张优惠券
      for (var i = 0; i < goodsList.length; i++) {//更新购买商品数量
        goodsList[i].number = goodsList[i].buy_num;
      }
      let cpId = '';
      if (cpIndex != '' && cpIndex > -1) {
        cpId = that.data.youhui[cpIndex].id;
      }
      wx.request({
        url: App.data.globalAPI + '/order/mall/post',
        data: {
          token: wx.getStorageSync('token'),
          goods: JSON.stringify(goodsList),
          pay: that.data.lastPayMoney,
          coupon_id: cpId,
          buy_vip: that.data.openVip?1:0
        },
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success(res) {
          const arr = res.data;
          var curPageArr = getCurrentPages();
          var page = curPageArr[curPageArr.length - 2];
          page.setData({
            firstNav: [],
            allListData: [],
            listScroll: 0,
            listTitle: '',//显示的二级标题名称
            firstIndex: 0,
            rightScroll: 0,
            showHotPackage: false
          })
          page.getBanner();
          page.getBoxGoodsList(); //获取分类
          page.getBoxLimit();//获取盒子限制
          page.clearShopCart();
        
          if (arr.error == 0) {    
            wx.redirectTo({
              url: '/pages/mine/lingshi_order/payment?total=' + that.data.lastPayMoney + '&account=' + that.data.userAccount + '&order_id= ' + arr.data.order.order_no
            })
          } else {
            wx.showToast({
              title: arr.msg,
              icon: 'none',
              duration: 800
            })
          }
        }, fail(res) {
          wx.showModal({
            title: '提示',
            content: '网络异常，请稍后重试！',
            showCancel: false,
            success(res) {
            }
          })
        }
      })
      
    }
  },

  // 选择优惠券
  goChoseDiscount: function () {
    if (this.data.youhui.length > 0) {
      wx.navigateTo({
        url: '../index_order_quan?list=' + JSON.stringify(this.data.youhui),
      })
    }
  },

})